package com.easyattendance.services;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.easyattendance.model.Class;
import com.easyattendance.model.Proxy;
import com.easyattendance.model.Section;
import com.easyattendance.model.Subject;
import com.easyattendance.model.SubjectClass;
import com.easyattendance.model.SubjectTeacher;
import com.easyattendance.model.Teacher;
import com.easyattendance.model.TimeTable;
import com.easyattendance.model.User;
import com.easyattendance.util.HibernateUtil;

public class AddTeacherService {

	/* Method to CREATE a Teacher in the database */
	   public synchronized boolean addTeacher(Teacher teacher){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      //boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	        	 session.save(teacher);
	           	 tx.commit();

	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return true;
	   }
	   
	   /* Method to update a Teacher in the database */
	   public synchronized boolean updateTeacher(Teacher teacher){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      //boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	        	 session.update(teacher);
	           	 tx.commit();

	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return true;
	   }
	   
	   /* Method to DELETE an teacher from the records */
	   public synchronized boolean deleteTeacher(String teacherId){
		   Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean flag = false;
	      try{
	         tx = session.beginTransaction();
	         List list  = session.createQuery("FROM User").list();
	         for(Iterator itr = list.iterator(); itr.hasNext(); ) {
	        	 User user = (User) itr.next();
	        	 
	        	 if(user.getUser_id().equals(teacherId)) {
	        		 session.delete(user);
	        		 break;
	        	 }
	         }
	        
	         /*Section section = getSectionBySectionEmail(emailId);
	         
	         session.delete(section);*/
	         tx.commit();
	         flag = true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return flag;
	   }
	   
	   public int getTeacherIdValue(String sectionName,String sectionId)
	   {
		   	Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        int value=0;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	           // SQLQuery query = session.createSQLQuery("select MAX(teacher_id) from tbl_teacher where substr(teacher_id,0,3)='"+sectionName+"'");
	            SQLQuery query = session.createSQLQuery("select MAX(teacher_id) from tbl_teacher group by section_id having section_id='"+sectionId+"'");
	            if(query.uniqueResult()!=null)
	            {
	            	String teacher_id=(String) query.uniqueResult();
	            	String teacher_counter=teacher_id.substring(11);
	            	value = Integer.parseInt(teacher_counter)+1;
	            }
	            else
	            	value=1;
	            
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
		   
		   return value;
	   }
	   
	   public boolean ifAlreadyExists(String teacherName) {
			 boolean flag = getUserByUserId(teacherName);
			 
			 return flag;
			 /*if(stud!=null && stud.getName().equals(studName) ){
				 return false;
			 }else{
				 return true;
			 }*/
		}
	   
	   public boolean ifAlreadyExists(Teacher newTeacher) {
			 boolean flag = false;
			 
			 Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List teachers = null;
		      try{
		         tx = session.beginTransaction();
		         teachers = session.createQuery("FROM Teacher").list(); 
		         for (Iterator iterator = teachers.iterator(); iterator.hasNext();){
		        	Teacher teacher = (Teacher) iterator.next(); 
		            if(teacher.equals(newTeacher)) {
		            	System.out.println("teacher already exists");
		            	flag = true;
		            	break;
		            }
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
			 
			 return flag;
			 /*if(stud!=null && stud.getName().equals(studName) ){
				 return false;
			 }else{
				 return true;
			 }*/
		}
		public boolean getUserByUserId(String teacherName) {
			 Session session = HibernateUtil.openSession();
			 Transaction tx = null;
			 //Teacher teacher = null;
			 Query query=null;
			 boolean flag = false;
			 try {
				 tx = session.getTransaction();
				 tx.begin();
				// tx = session.beginTransaction();
				 query = session.createQuery("from Teacher where teacher_name='"+teacherName+"'");
				 List list = query.list();
				 			 
				 if (list.isEmpty()) {
					 flag = false;
				 }
				 else {
					 flag = true;
				 }
				 if (!tx.wasCommitted()) {
					 tx.commit();
				 }
					 
			 } catch (Exception e) {
				 if (tx != null) {
					 tx.rollback();
				 }
				 e.printStackTrace();
			 } finally {
				 session.close();
			 }
			return flag;
		}
		
		public Teacher getTeacherByTeacherName(String teacherName) {
	        Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        Teacher user = null;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	            Query query = session.createQuery("from Teacher where teacher_name='"+teacherName+"'");
	            user = (Teacher)query.uniqueResult();
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
	        return user;
	    }
		
		public Teacher getTeacherById(String teacherId) {
	        Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        Teacher user = null;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	            Query query = session.createQuery("from Teacher where teacher_id='"+teacherId+"'");
	            user = (Teacher)query.uniqueResult();
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
	        return user;
	    }
		
		public Teacher getTeacherByEmailId(String teacherEmailId) {
	        Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        Teacher user = null;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	            Query query = session.createQuery("from Teacher where email_id='"+teacherEmailId+"'");
	            user = (Teacher)query.uniqueResult();
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
	        return user;
	    }
		
		public String getSectionEmailIdByTeacherId(String teacherEmailId) {
	        Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        Teacher user = null;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	            Query query = session.createQuery("from Teacher where email_id='"+teacherEmailId+"'");
	            user = (Teacher)query.uniqueResult();
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
	        return user.getSection().getEmail_id();
	    }
	   
		public String getSectionIdByTeacherId(String teacherEmailId) {
	        Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        Teacher user = null;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	            Query query = session.createQuery("from Teacher where email_id='"+teacherEmailId+"'");
	            user = (Teacher)query.uniqueResult();
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
	        return user.getSection().getSection_id();
	    }
		/* Method to  READ all the Teachers values */
		   public List listTeachers( ) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List teachers = null;
		      try{
		         tx = session.beginTransaction();
		         teachers = session.createQuery("FROM Teacher").list(); 
		         for (Iterator iterator = teachers.iterator(); iterator.hasNext();){
		        	Teacher teacher = (Teacher) iterator.next(); 
		            System.out.print("Teacher Name: " + teacher.getTeacher_name()); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return teachers;
		   }
		   
		   /* Method to  READ all the teachers values of particular section */
		   public List<Teacher> listTeachers(String sectionEmailId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List<Teacher> teachers = null;
		      try{
		         tx = session.beginTransaction();
		         /*Query query = session.createQuery("from Department where dept_email_id='"+currentUser+"'");
		         Department user = (Department)query.uniqueResult();*/
		         Query query = session.createQuery("FROM Section where email_id='"+sectionEmailId+"'");
		         Section section = (Section) query.uniqueResult();
		         teachers = session.createQuery("FROM Teacher where section_id='"+section.getSection_id()+"'").list(); 
		         for (Iterator iterator = teachers.iterator(); iterator.hasNext();){
		        	Teacher teacher = (Teacher) iterator.next(); 
		            System.out.print("TeacherId: " + teacher.getTeacher_id()); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return teachers;
		   }

		   /* Method to  READ all the teachers values of particular department except the passed teacher*/
		   public List<Teacher> listTeachers(String deptEmailId, String teacherId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List<Teacher> teachers = null;
		      try{
		         tx = session.beginTransaction();
		         Query query = session.createQuery("from Section where email_id='"+deptEmailId+"'");
		         Section user = (Section)query.uniqueResult();
		         teachers = session.createQuery("FROM Teacher where section_id='"+user.getSection_id()+"' and teacher_id!='"+teacherId+"'").list(); 
		         for (Iterator iterator = teachers.iterator(); iterator.hasNext();){
		        	Teacher teacher = (Teacher) iterator.next(); 
		            System.out.print("TeacherId: " + teacher.getTeacher_id()); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return teachers;
		   }
		   
		   /* Method to UPDATE teacher as class teacher */
		   public synchronized void updateTeacherToClassTeacher(Teacher teacher){
		      Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      try{
		         tx = session.beginTransaction();
		         teacher.setClassTeacher(true);
				 session.update(teacher); 
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		   }
		   
		   /* Method to remove teacher as class teacher */
		   public synchronized void removeTeacherAsClassTeacher(Teacher teacher){
		      Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      try{
		         tx = session.beginTransaction();
		         teacher.setClassTeacher(false);
				 session.update(teacher); 
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		   }
		   
		   /* Method to check if a teacher is class teacher */
		   public boolean ifClassTeacher(String teacherEmailId){
		      Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      Teacher user=null;
		      try{
		         tx = session.beginTransaction();
		         Query query = session.createQuery("from Teacher where teacher_email_id='"+teacherEmailId+"'");
		         user = (Teacher)query.uniqueResult();
		         
		        
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return user.isClassTeacher();
		   }
		   
		   /* Method to  READ all the teachers who are not class teachers of particular Section */
		   public List<Teacher> listNoneClassTeachers(String deptEmailId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List<Teacher> teachers = null;
		      try{
		         tx = session.beginTransaction();
		         Query query = session.createQuery("from Section where email_id='"+deptEmailId+"'");
		         Section user = (Section)query.uniqueResult();
		         teachers = session.createQuery("FROM Teacher where section_id='"+user.getSection_id()+"' and isClassTeacher='"+false+"'").list(); 
		         for (Iterator iterator = teachers.iterator(); iterator.hasNext();){
		        	Teacher teacher = (Teacher) iterator.next(); 
		            System.out.print("TeacherId: " + teacher.getTeacher_id()); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return teachers;
		   }
		   
		   /* Method to  READ all the subjects that are not occupied on a day for a timeslot */
		   public List<Teacher> listTeachersOnDayForTimeSlot(String day, String timeSlot, String teacherEmail) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List<Teacher> teachers = new ArrayList<Teacher>();
		      
		      List<TimeTable> timeTable = null;
		      AddTeacherService teacherService = new AddTeacherService();
		      AddClassService ClassService = new AddClassService();
		      try{
		         tx = session.beginTransaction();
		         String deptId = teacherService.getSectionIdByTeacherId(teacherEmail);
		         String ClassId = ClassService.getClassIdByTeacherId(teacherEmail);
		         
		         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		         /*Date tempSlot=null;
				 try {
					tempSlot = format.parse("2013-10-10 "+timeSlot+":00");
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
		         String tempSlot="2013-10-10 "+timeSlot+":00";
		        
				 /*List<TimeTable> test = session.createQuery("FROM TimeTable").list();
				 for (Iterator<TimeTable> iterator = test.iterator(); iterator.hasNext();){
			        	TimeTable tempTT = (TimeTable) iterator.next(); 
			            System.out.println("SubjectName: " + tempTT.getSubject_id());
			            System.out.println("TIMESLOT: " + tempTT.getTime_slot());
				 }*/
		         timeTable = session.createQuery("FROM TimeTable where day_of_week ='"+day+"' and time_slot='"+tempSlot+"' and section_id='"+deptId+"'").list();
		         
		         if(timeTable.isEmpty()) {
		        	 teachers = session.createQuery("FROM Teacher where section_id='"+deptId+"'").list();
		         }
		         else {
		        	 for (Iterator<TimeTable> iterator = timeTable.iterator(); iterator.hasNext();){
				        	TimeTable tempTT = (TimeTable) iterator.next();
				        	
				        	List query = session.createQuery("FROM Teacher where teacher_id !='"+tempTT.getTeacher().getTeacher_id()+"' "
				            		+ "and section_id='"+deptId+"'").list();
				           for (Iterator teacherIterator = query.iterator(); teacherIterator.hasNext();) {
				        	   Teacher tempTeacher = (Teacher) teacherIterator.next();
				        	   	teachers.add(tempTeacher);
					            System.out.println("SIZE IN java: "+teachers.size());
				           }
				            
				            /*for (Iterator<Subject> ttIterator = tempSubject.iterator(); iterator.hasNext();){
				            	subjects.add((Subject) ttIterator.next());	             
				            }*/
			         }
		         }
		         
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return teachers;
		   }
		   
		   /* Method to  READ the teacher who is occupied on a day for a timeslot in a semester */
		   public TimeTable listTimeTableOnDayForTimeSlot(String day, String timeSlot, String ClassId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List<Teacher> teachers = new ArrayList<Teacher>();
		      
		      TimeTable timeTable = null;
		      AddTeacherService teacherService = new AddTeacherService();
		      AddClassService ClassService = new AddClassService();
		      try{
		         tx = session.beginTransaction();
		         //String deptId = teacherService.getDeptIdByTeacherId(teacherEmail);
		         String deptId = ClassService.getClassById(ClassId).getSection().getSection_id();
		         
		         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		         
		         String tempSlot="2013-10-10 "+timeSlot+":00";
		        
		         Query query = session.createQuery("FROM TimeTable where day_of_week ='"+day+"' and time_slot='"+tempSlot+"'"
		         		+ " and section_id='"+deptId+"' and class_id='"+ClassId+"'");
		         timeTable = (TimeTable) query.uniqueResult();
		         
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      if(timeTable == null) {
		    	  return null;
		        }
		      else {
		    	  return timeTable;
		      }
		      
		   }
		   
		   public void SendMail(String teacherEmailId)
		   {
			   final String username = "merin1590@gmail.com";
				final String password = "jesuschrist123";
		 
				Properties props = new Properties();
				props.put("mail.smtp.auth", "true");
				props.put("mail.smtp.starttls.enable", "true");
				props.put("mail.smtp.host", "smtp.gmail.com");
				props.put("mail.smtp.port", "587");
		 
				javax.mail.Session session = javax.mail.Session.getInstance(props,
				  new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				  });
		 
				try {
		 
					Message message = new MimeMessage(session);
				
					message.setFrom(new InternetAddress("merin1590@gmail.com"));
					message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse("merin1590@gmail.com")); // teacherEmailId should be passed here afterwards
					/* message.setRecipients(Message.RecipientType.TO,
						InternetAddress.parse(teacherEmailId)); */
					message.setSubject("Request for account Activation");
					
					
					Teacher teacher=getTeacherByEmailId(teacherEmailId);
					String teacher_name=teacher.getTeacher_name()+" "+teacher.getTeacher_lname();
					LoginService loginservice=new LoginService();
					User user=(User) loginservice.getUserByUserId(teacherEmailId,"User");
					String token=user.getSecret_key();
					
					String msg_text="Hi, "+teacher_name
							+ "\n\n Please click the below link to activate your account on Easy Attendance"
							+ "\n\n http://localhost:8080/Attendance/views/activationSuccess.jsp?token="+token;
					
							// Create the message part 
							MimeBodyPart messageBodyPart = new MimeBodyPart();

							// Fill the message
							messageBodyPart.setContent(msg_text,"text/html");

							MimeMultipart multipart = new MimeMultipart();
							multipart.addBodyPart(messageBodyPart);

							// Put parts in message
							message.setContent(multipart);
							message.setText(msg_text);
						Transport.send(message);
		 
					System.out.println("Mail sent!!");
		 
				} catch (MessagingException e) {
					throw new RuntimeException(e);
				} 

		   }
		   
		   /* Method to increment teacher_subject counter for all teacher's subjects in that class for sysdate*/
		   
		   public void incrementLectureStatus(String sectionEmailId, String classId) {
			   Date sysDate = new Date();
			   
			   AddProxyService proxyService = new AddProxyService();
			   AddAllTimeSlotsService timeTableService = new AddAllTimeSlotsService();
			   String[] timeSlots = timeTableService.listAllTimeSlotsBySection(sectionEmailId);
			   String tmpTime = null;
			   String[] teacherIds = new String[9];
			   String[] subjectIds = new String[9];
			   TimeTable timeTable = null;
			   Proxy proxy = null;
			   SubjectTeacher subjectTeacher = null;
			   
			   int today = sysDate.getDay();
			   String day = null;
			   
			   switch(today){
			   	case 0:
				   day = "Sunday";
				   break;
			   	case 1:
				   day = "Monday";
				   break;
			   	case 2:
				   day = "Tuesday";
				   break;
			   	case 3:
				   day = "Wednesday";
				   break;
			   	case 4:
				   day = "Thursday";
				   break;
			   	case 5:
				   day = "Friday";
				   break;
			   	case 6:
				   day = "Saturday";
				   break;
				 
			   }
			   Session session = HibernateUtil.openSession();
				Transaction tx = null;
				
				try {
					tx = session.beginTransaction();
					
					for(int i=0, j=0; i<timeSlots.length; i++) {
						tmpTime = "2013-10-10 "+timeSlots[i]+":00";
						
						Query query = session.createQuery("FROM TimeTable WHERE day_of_week='" + day + "' and time_slot='"+tmpTime+"' "
								+ "and class_id='"+classId+"'");
						
						
						if(query.uniqueResult()!=null) {
							timeTable = (TimeTable) query.uniqueResult();
							
							proxy = proxyService.getProxyOnDayForTimeSlot(day, tmpTime, classId, timeTable.getSubject_id());
							
							if(proxy!=null) {
								subjectIds[j] = proxy.getProxy_subject_id();
								teacherIds[j++] = proxy.getProxy_teacher_id();
							}
							else {
								subjectIds[j] = timeTable.getSubject_id();
								teacherIds[j++] = timeTable.getTeacher_id();
							}
						}
					}
					
					for(int j=0; j<teacherIds.length; j++) {
						Query query = session.createQuery("FROM SubjectTeacher where teacher_id='"+teacherIds[j]+"' and subject_id='"+subjectIds[j]+"'");
						if(query.uniqueResult()!=null) {
							subjectTeacher = (SubjectTeacher) query.uniqueResult();
							//proxy settings
							
							subjectTeacher.setLecture_status( (subjectTeacher.getLecture_status()) +1);
							
							session.save(subjectTeacher);
						}
					}
					tx.commit();
					} catch (HibernateException e) {
						if (tx != null)
							tx.rollback();
						e.printStackTrace();
					} finally {
						session.close();
					}
			   
		   	}
  
}
